package com.finance.system.configure.mvc;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Component
public class StringToLocalDateTimeConverter implements Converter<String,LocalDateTime> {

    @Value("${finance.system.date-pattern}")
    private String pattern;

    private DateTimeFormatter dateTimeFormatter;

    @PostConstruct
    public void initDateFormatter(){
        if(this.dateTimeFormatter != null) return;
        this.dateTimeFormatter = DateTimeFormatter.ofPattern(pattern);
    }

    @Override
    public LocalDateTime convert(String source) {
        if(StringUtils.isEmpty(source)){
            return null;
        }
        LocalDateTime parse = LocalDateTime.parse(source,dateTimeFormatter);

        return parse;
    }
}
